<template>
  <view class="main-box">
    <view class="container">
      <!-- 轮播图 -->
      <view class="swiper-warp">
        <swiper
          class="swiper"
          circular
          :indicator-dots="indicatorDots"
          :autoplay="autoplay"
          :interval="interval"
          :duration="duration"
          indicator-color="#d0d0d0"
          indicator-active-color="#bb7755">
          <swiper-item v-for="item in imgList" :key="item.id">
            <image
              :src="`http://localhost:8080/api/swiperImgs/${item.imgUrl}`"></image>
          </swiper-item>
        </swiper>
      </view>

      <!-- 价格 甜品名 销量 库存 -->
      <view class="dessert-show">
        <view class="show-head">
          <view class="price-name">
            <text class="price">{{ '￥' + dessertInfo.dessertPrice }}</text>
            <text class="name">{{ dessertInfo.dessertName }}</text>
          </view>
          <view class="star-icon" @click="starDessert">
            <up-icon name="star" size="26" v-if="isStar === false"></up-icon>
            <up-icon
              name="star-fill"
              color="#f9acb4"
              size="26"
              v-else></up-icon>
            <text>{{ isStar === false ? '收 藏' : '已收藏' }}</text>
          </view>
        </view>
        <view class="line"></view>
        <view class="sale-inventory">
          <text class="sale">销量:{{ dessertInfo.sales }}</text>
          <text class="inventory">库存:{{ dessertInfo.inventory }}</text>
        </view>
      </view>

      <!-- 描述 规格 -->
      <view class="dessert-desc">
        <text style="font-size: 32rpx; font-weight: bold">商品详情</text>
        <view class="desc-content">
          <text
            style="font-size: 28rpx; font-weight: bold; white-space: nowrap">
            描述：
          </text>
          <text style="font-size: 28rpx; color: #666">
            {{ dessertInfo.dessertDesc }}
          </text>
        </view>
        <view class="specs">
          <text style="font-size: 28rpx; font-weight: bold">规格：</text>
          <text style="font-size: 28rpx; color: #666">
            {{ dessertInfo.specs }}/份
          </text>
        </view>
      </view>

      <!-- 底部操作栏 -->
      <view class="fotter">
        <uni-goods-nav
          :fill="true"
          :options="options"
          :buttonGroup="buttonGroup"
          @click="onClick"
          @buttonClick="buttonClick" />
      </view>
    </view>
  </view>
</template>

<script setup>
import { onLoad, onUnload } from '@dcloudio/uni-app'
import { ref } from 'vue'
import {
  getDessertImgsByDessertId,
  getDessertByIdService,
} from '../../api/dessert.js'
import { useUserStore } from '../../stores/user.js'
import { useCartStore } from '../../stores/cart.js'
import { addStarService, delStarService } from '../../api/star.js'
import { addCartService } from '../../api/cart.js'

const userStore = useUserStore()
const carStore = useCartStore()
let goodsNum = carStore.goodsNum
// 用户收藏列表
const starList = userStore.starList
const starInfo = ref({
  dessertId: '',
  userId: '',
})
const isStar = ref(false)

const dessertInfo = ref({})
const imgList = ref([])
onLoad(async (option) => {
  const id = JSON.parse(decodeURIComponent(option.id))
  const res = await getDessertByIdService(id)
  dessertInfo.value = res.data
  // 获取甜品详情轮播图数据
  const imgs = await getDessertImgsByDessertId(id)
  imgList.value = imgs.data
  // 遍历用户收藏列表，当dessertId相同时，收藏按钮高亮
  starList.forEach((item) => {
    if (item.dessertId === dessertInfo.value.id) {
      isStar.value = true
    }
  })
})
onUnload(() => {
  uni.$emit('update')
})

// 轮播图的设置
const indicatorDots = ref(true) // 是否显示面板指示点
const autoplay = ref(true) //  是否自动切换
const interval = ref(3000) // 自动切换间隔时间
const duration = ref(500) // 滑动动画时长

// 收藏
const starDessert = async () => {
  if (Object.keys(userStore.userInfo).length === 0) {
    uni.showModal({
      title: '温馨提示',
      content: '您还未登录，请先登录',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({
            url: '/pages/loginAndRegister/loginAndRegister',
          })
        }
      },
    })
  } else {
    isStar.value = !isStar.value
    starInfo.value.dessertId = dessertInfo.value.id
    starInfo.value.userId = userStore.userInfo.userId
    if (isStar.value) {
      const res = await addStarService(starInfo.value)
      if (res.code === '0') {
        uni.showToast({
          title: '收藏成功',
          icon: 'success',
        })
        userStore.insertStarList(res.data)
      }
    } else {
      const res = await delStarService(starInfo.value)
      userStore.delStarList(res.data.dessertId)
      uni.showToast({
        title: '取消收藏',
        icon: 'none',
      })
    }
  }
}

// 底部选择
const options = ref([
  {
    icon: 'shop',
    text: '店铺',
  },
  {
    icon: 'cart',
    text: '购物车',
    info: goodsNum,
  },
])
const buttonGroup = ref([
  {
    text: '加入购物车',
    backgroundColor: '#997d6f',
    color: '#fff',
  },
  {
    text: '立即购买',
    backgroundColor: '#7e675b',
    color: '#fff',
  },
])

// 点击图标事件
const onClick = (e) => {
  // 如果点击店铺，跳转到首页
  if (e.content.text === '店铺') {
    uni.switchTab({
      url: '/pages/index/index',
    })
  } else {
    // 否则跳转到购物车列表页
    uni.switchTab({
      url: '/pages/myCar/myCar',
    })
  }
}
// 点击“加入购物车或立即购买”
const cartInfo = ref({})
const buttonClick = async (e) => {
  if (Object.keys(userStore.userInfo).length === 0) {
    uni.showModal({
      title: '温馨提示',
      content: '您还未登录，请先登录',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({
            url: '/pages/loginAndRegister/loginAndRegister',
          })
        }
      },
    })
  } else {
    if (e.content.text === '加入购物车') {
      // 购物车加入对应甜品
      cartInfo.value.userId = userStore.userInfo.userId
      cartInfo.value.dessertId = dessertInfo.value.id
      cartInfo.value.num = 1
      
      const res = await addCartService(cartInfo.value)
      cartInfo.value.id = res.data
      carStore.addCar(cartInfo.value)
      if (res.code === '0') {
        uni.showToast({
          title: carStore.showMsg ? carStore.showMsg : '添加成功',
          icon: 'none',
        })
      }
      // 购物车数量加1
      carStore.setGoodsNum(carStore.carList.length)
      goodsNum = carStore.goodsNum
      options.value[1].info = goodsNum
      
    } else {
      // 立即购买
      if(dessertInfo.value.inventory <= 0) {
        uni.showToast({
          title: '抱歉,该甜品库存不足',
          icon: 'none'
        })
        return false
      }
      // 立即购买
      cartInfo.value.userId = userStore.userInfo.userId
      cartInfo.value.dessertId = dessertInfo.value.id
      cartInfo.value.num = 1
      cartInfo.value.dessert = dessertInfo.value
      uni.navigateTo({
        url: `/pages/bookOrder/bookOrder?info=${encodeURIComponent(
          JSON.stringify(cartInfo.value)
        )}`,
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.main-box {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  .container {
    width: 90%;
    height: 80%;
    margin: 0 auto;
    background-color: #fff;
    box-shadow: 0 0 30rpx rgba(0, 0, 0, 0.08);
    border-radius: 20rpx;
    overflow: hidden;
    box-sizing: border-box;
    .swiper-warp {
      .swiper {
        width: 100%;
        height: 400rpx;
        border-radius: 20rpx;
        image {
          width: 100%;
          height: 400rpx;
          border-radius: 20rpx;
        }
      }
    }
    .dessert-show {
      width: 100%;
      height: 200rpx;
      overflow: hidden;
      .line {
        width: 90%;
        height: 3rpx;
        background-color: #c7c7c7;
        margin: 0 auto;
      }
      .show-head {
        width: 100%;
        display: flex;
        .price-name {
          width: 90%;
          height: 130rpx;
          display: flex;
          flex-direction: column;
          box-sizing: border-box;
          margin-left: 20rpx;
          .price {
            font-size: 36rpx;
            color: #f9acb4;
            font-weight: bold;
          }
          .name {
            font-size: 40rpx;
            color: #000;
            font-weight: bold;
            margin-top: 5rpx;
          }
        }
        .star-icon {
          width: 80rpx;
          display: flex;
          flex-direction: column;
          margin-right: 20rpx;
          margin-top: 10rpx;
          justify-content: center;
          align-items: center;
          text {
            text-align: center;
            font-size: 20rpx;
            color: #666;
          }
        }
      }
      .sale-inventory {
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 90%;
        height: 50rpx;
        box-sizing: border-box;
        margin: 6rpx auto;
        .sale {
          font-size: 28rpx;
          color: #666;
        }
        .inventory {
          font-size: 28rpx;
          color: #666;
        }
      }
    }
    .dessert-desc {
      width: 90%;
      height: 260rpx;
      overflow: hidden;
      box-sizing: border-box;
      margin: 30rpx auto;
      .desc-content {
        width: 100%;
        height: 120rpx;
        display: flex;
        flex-direction: row;
        margin-top: 25rpx;
      }
      .specs {
        height: 10rpx;
        display: flex;
      }
    }
    .fotter {
      width: 100%;
      height: 80rpx;
      margin-top: -50rpx;
    }
  }
}
</style>
